package com.lfd.netty.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @项目名： spring-emq
 * @包名： com.lfd.netty.netty
 * @文件名: NettyServer
 * @创建者: liufudong@szyh-smart.com
 * @创建时间: 2024/10/5 10:38
 * @描述：服务端实现
 */
@Slf4j
public class NettyServer {
    private final int port;

    // 存储在线客户端的映射关系
    private final Map<String, ChannelHandlerContext> clients = new HashMap<>();
    public NettyServer(final int port) {
        this.port = port;
    }

    public void start() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, String msg) {
                                    log.info("NettyServer Received message: " + msg);
                                    //Netty 服务器中向客户端发送一条消息。
                                    ctx.writeAndFlush("Message received: " + msg);
                                }

                                @Override
                                public void channelActive(ChannelHandlerContext ctx) {
                                    log.info("NettyServer Client channelActive remoteAddress: " + ctx.channel().remoteAddress());
                                    // 获取客户端的地址
                                    String clientAddress = ctx.channel().remoteAddress().toString();
                                    // 添加到在线客户端列表
                                    clients.put(clientAddress, ctx);
                                    log.info("NettyServer Client channelActive clientAddress: " + clientAddress);
                                    // 可以在此处发送欢迎消息
                                    ctx.writeAndFlush("Welcome, " + clientAddress + "!");
                                }

                                @Override
                                public void channelInactive(ChannelHandlerContext ctx) {
                                    log.info("NettyServer Client disconnected: " + ctx.channel().remoteAddress());

                                    // 获取客户端的地址
                                    String clientAddress = ctx.channel().remoteAddress().toString();
                                    // 添加到在线客户端列表
                                    clients.put(clientAddress, ctx);
                                    log.info("NettyServer Client connected: " + clientAddress);
                                    // 可以在此处发送欢迎消息
                                    ctx.writeAndFlush("NettyServer Welcome, " + clientAddress + "!");
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                    log.info("NettyServer Client exceptionCaught: " + cause.getMessage());
                                    cause.printStackTrace();
                                    ctx.close();
                                }
                            });
                        }
                    })
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture f = serverBootstrap.bind(port).sync();
            log.info("NettyServer Server started on port " + port);
            f.channel().closeFuture().sync();
        } finally {
            log.info("NettyServer finally " );
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new NettyServer(8080).start();
    }
}